package com.filiebo.demo.tictoc;

import java.util.List;

public class TicToc {

    private Character[][] board = {{'\0', '\0', '\0'}, {'\0', '\0', '\0'}, {'\0', '\0', '\0'}};

    private char lastPlayer = '\0';

    private static final int SIZE = 3;

    public String play(int x, int y) {

        if (x > 3) {
            throw new RuntimeException();
        }

        if (y > 3) {
            throw new RuntimeException();
        }

        lastPlayer = nextPlayer();

        setBox(x, y,lastPlayer);

        if (isWin(x, y)) {
            return lastPlayer + " is the winner";
        } else if (isDraw()) {
            return "It ends in a draw";
        } else {
            return "No Winner";
        }
    }


    public void setBox(int x, int y,char lastPlayer) {
        if (board[x - 1][y - 1] != '\0') {
            throw new RuntimeException("already serverIve board");
        } else {
            board[x - 1][y - 1] = lastPlayer;
        }
    }

    public char nextPlayer() {
        if (lastPlayer == 'X') {
            return 'O';
        }
        return 'X';
    }

    public boolean isWin(int x, int y) {

        char current, diagion1, diagion2, diagion3;
        //diagion1 = diagion2 = diagion3 = '\0';

        diagion1 = board[0][y-1];
        diagion2 = board[1][y-1];
        diagion3 = board[2][y-1];
        if (diagion1 == diagion2 && diagion2 == diagion3) {
            return true;
        }

        diagion1 = board[x-1][0];
        diagion2 = board[x-1][1];
        diagion3 = board[x-1][2];
        if (diagion1 == diagion2 && diagion2 == diagion3) {
            return true;
        }

//        diagion1 = board[x][0];
//        diagion2 = board[x][1];
//        diagion3 = board[x][2];
//        if (diagion1 == diagion2 && diagion2 == diagion3) {
//            return true;
//        }

        return false;
    }


    public boolean isDraw() {
        for (int x = 0; x < SIZE; x++) {
            for (int y = 0; y < SIZE; y++) {
                if (board[x][y] == '\0') {
                    return false;
                }
            }
        }
        return true;
    }
}
